from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import win32gui, win32con, win32api
import time


def loadLocalFile(path):
    """加载本地文件"""
    class_name = "#32770"  # 请替换成实际的窗口类名
    window_handle = win32gui.FindWindow(class_name, r"打开")
    child_handle = win32gui.FindWindowEx(window_handle, None, "ComboBoxEx32", None)
    child_handle = win32gui.FindWindowEx(child_handle, None, "ComboBox", None)
    child_handle = win32gui.FindWindowEx(child_handle, None, "Edit", None)
    child_button = win32gui.FindWindowEx(window_handle, None, "Button", r"打开(&O)")
    parent = win32gui.GetParent(window_handle)
    print("父窗口句柄: ", hex(parent))
    print("窗口句柄: ", hex(window_handle))
    print("控件句柄：", hex(child_button))
    for ch in path:
        win32gui.SendMessage(child_handle, win32con.WM_CHAR, ord(ch), 0)
        time.sleep(0.05)
    # win32api.keybd_event(13, 0, 0, 0)
    # time.sleep(0.05)
    # win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0)
    # position = win32api.MAKELONG(5, 5)  # x,y为点击点相对于该窗口的坐标
    # win32api.SendMessage(
    #     child_button, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, position
    # )  # 向窗口发送模拟鼠标点击
    # time.sleep(0.05)
    # win32api.SendMessage(
    #     child_button, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, position
    # )  # 模拟释放鼠标左键


if __name__ == "__main__":
    driver = webdriver.Edge()
    driver.get("https://www.baidu.com")
    current_handle = driver.current_window_handle
    print("当前窗口句柄: ", current_handle)
    loadLocalFile(r"D:\tb9\Working\hedrads\res\audio.wav")
    # loadLocalFile(r"D:\tb9\Working\hedrads\res\image.png")
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(1))
